package com.lingnan.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingnan.entity.po.JobViewRecord;
import com.lingnan.mapper.JobPositionMapper;
import com.lingnan.mapper.JobViewRecordMapper;
import com.lingnan.service.JobViewRecordService;
import com.lingnan.vo.JobViewRecordVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class JobViewRecordServiceImpl extends ServiceImpl<JobViewRecordMapper, JobViewRecord>
        implements JobViewRecordService {
    
    @Resource
    private JobPositionMapper jobPositionMapper;
    
    @Override
    public boolean recordJobView(Long userId, Long jobId, String ipAddress, String userAgent) {
        // 检查用户是否已经浏览过该职位
        if (hasUserViewedJob(userId, jobId)) {
            log.info("用户{}已浏览过职位{}, 跳过重复计数", userId, jobId);
            return true;
        }
        
        try {
            // 创建浏览记录
            JobViewRecord viewRecord = new JobViewRecord();
            viewRecord.setUserId(userId);
            viewRecord.setJobId(jobId);
            viewRecord.setViewTime(new Date());
            viewRecord.setIpAddress(ipAddress);
            viewRecord.setUserAgent(userAgent);
            viewRecord.setCreatedAt(new Date());
            
            // 保存浏览记录
            boolean saveResult = this.save(viewRecord);
            
            if (saveResult) {
                // 增加职位浏览计数
                int updateResult = jobPositionMapper.incrementViewCount(jobId);
                log.info("职位{}浏览计数更新结果: {}", jobId, updateResult);
                return updateResult > 0;
            }
            
            return false;
        } catch (DuplicateKeyException e) {
            // 处理并发情况下的重复插入
            log.warn("用户{}浏览职位{}记录已存在，跳过插入", userId, jobId);
            return true;
        } catch (Exception e) {
            log.error("记录用户{}浏览职位{}失败", userId, jobId, e);
            throw new RuntimeException("记录浏览失败", e);
        }
    }
    
    @Override
    public boolean hasUserViewedJob(Long userId, Long jobId) {
        return baseMapper.checkUserViewRecord(userId, jobId) > 0;
    }
    
    @Override
    public int getJobViewUserCount(Long jobId) {
        return baseMapper.getJobViewUserCount(jobId);
    }
    
    @Override
    public IPage<JobViewRecordVO> getUserViewRecords(Long userId, int current, int size) {
        IPage<JobViewRecordVO> page = new Page<>(current, size);
        return baseMapper.getUserViewRecords(page, userId);
    }
}